import { _decorator, Component, Node, Label, Vec3, Color, v3, UITransform, AudioClip } from 'cc';
const { ccclass, property } = _decorator;

import { SSS_Consts } from "../../../../Script/Data/SSS_Consts";
import { bdlMgr } from "../../../../Script/Manager/BundleManager_S";
import { Minesweeper_GameData } from "../Data/Minesweeper_GameData";
import Minesweeper_GamePanel from "../UI/Minesweeper_GamePanel";
import Minesweeper_GameManager from "./Minesweeper_GameManager";
import { SSS_AudioManager } from 'db://assets/Script/Manager/SSS_AudioManager';

@ccclass('MinesweeperGrid')
export default class Minesweeper_Grid extends Component {
        @property(Node)
        未翻开图片: Node | null = null;
        @property(Node)
        雷: Node | null = null;
        @property(Node)
        旗子: Node | null = null;

        @property(Node)
        touch_node: Node | null = null;
        @property(Label)
        Label_count: Label | null = null;
        @property(Node)
        red: Node | null = null;
        @property(Label)
        Label_pos: Label | null = null;

        col: number = 0;
        row: number = 0;
        id: number = 0;
        //    // block: S2048_Block = null;
        是否是雷 = false;	//这个格子有没有地雷
        周围雷数量 = 0;	//这个格子周围8个格子里有几个雷
        是否翻开 = false; //这个格子是否已经被玩家翻开
        是否插旗 = false;
        //    // 初始化
        init(_col: number, _row: number, _id: number) {
                this.col = _col;
                this.row = _row;
                this.id = _id;

                // this.block = null;

                this.InitWidthAndHeight(Minesweeper_GameData.size, Minesweeper_GameData.size);
                this.InitPosition();
                this.Refresh();
                this.AddListener();
        }
        AddListener() {
                // console.log(`AddListener`);

                this.touch_node.on(Node.EventType.TOUCH_END, this.On_click, this);
        }
        On_click() {
                console.log(`On_click`);
                console.log(`Minesweeper_GameData.状态`, Minesweeper_GameData.状态);

                // 如果点击的是已翻开的数字，无论什么状态都尝试自动展开
                if (this.是否翻开 && this.周围雷数量 > 0) {
                        this.expandAroundIfFlagMatch();
                        return;
                }

                // 其他情况按状态处理
                if (Minesweeper_GameData.状态 == `扫雷`) {
                        this.revealCell(this.row, this.col);

                        bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, `audio/tile click`, AudioClip).then(res => {
                                SSS_AudioManager.Instance.playSFX(res, false);
                        });
                }
                else {
                        this.toggleFlag(this.row, this.col);

                        bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, `audio/click`, AudioClip).then(res => {
                                SSS_AudioManager.Instance.playSFX(res, false);
                        });
                }
        }
        //    // 新增：点击已翻开的数字时自动展开周围未插旗未翻开的格子
        expandAroundIfFlagMatch() {
                console.log(`expandAroundIfFlagMatch: 当前数字${this.周围雷数量}`);

                // 统计周围插旗数量
                let flagCount = 0;
                for (let dr = -1; dr <= 1; dr++) {
                        for (let dc = -1; dc <= 1; dc++) {
                                if (dr === 0 && dc === 0) continue;
                                const newRow = this.row + dr;
                                const newCol = this.col + dc;
                                if (
                                        newRow >= 0 &&
                                        newRow < Minesweeper_GameData.row &&
                                        newCol >= 0 &&
                                        newCol < Minesweeper_GameData.col
                                ) {
                                        const grid = Minesweeper_GameData.arrGrids[newRow][newCol];
                                        if (grid && grid.是否插旗) flagCount++;
                                }
                        }
                }

                console.log(`周围插旗数量: ${flagCount}, 需要数量: ${this.周围雷数量}`);

                // 如果插旗数量等于数字，自动翻开周围未插旗未翻开的格子
                if (flagCount === this.周围雷数量) {
                        console.log(`开始自动展开周围格子`);
                        for (let dr = -1; dr <= 1; dr++) {
                                for (let dc = -1; dc <= 1; dc++) {
                                        if (dr === 0 && dc === 0) continue;
                                        const newRow = this.row + dr;
                                        const newCol = this.col + dc;
                                        if (
                                                newRow >= 0 &&
                                                newRow < Minesweeper_GameData.row &&
                                                newCol >= 0 &&
                                                newCol < Minesweeper_GameData.col
                                        ) {
                                                const grid = Minesweeper_GameData.arrGrids[newRow][newCol];
                                                if (grid && !grid.是否插旗 && !grid.是否翻开) {
                                                        console.log(`展开格子: row=${newRow}, col=${newCol}`);
                                                        // 直接执行翻开逻辑，避免被revealCell的检查阻止
                                                        this.forceRevealCell(newRow, newCol);
                                                }
                                        }
                                }
                        }
                } else {
                        console.log(`插旗数量不匹配，不展开`);
                }
        }
        //    // 新增：强制翻开格子的方法（用于自动展开）
        forceRevealCell(row: number, col: number) {
                const grid = Minesweeper_GameData.arrGrids[row][col];
                if (!grid) return;

                // 直接翻开当前格子
                grid.是否翻开 = true;
                Minesweeper_GameData.已翻格子数++;
                grid.Refresh();

                // 胜利判断
                const 总格子数 = Minesweeper_GameData.row * Minesweeper_GameData.col;
                const 雷数 = Minesweeper_GameData.雷数量;

                if (Minesweeper_GameData.已翻格子数 === 总格子数 - 雷数) {
                        console.log("恭喜！你赢了！");
                        Minesweeper_GameManager.Instance.Win();
                        return;
                }

                // 如果是雷，游戏结束
                if (grid.是否是雷) {
                        console.log("踩雷了！");
                        Minesweeper_GameManager.Instance.Lose();
                        return;
                }

                // 如果周围没有雷，递归展开周围格子
                if (grid.周围雷数量 === 0) {
                        for (let dr = -1; dr <= 1; dr++) {
                                for (let dc = -1; dc <= 1; dc++) {
                                        if (dr === 0 && dc === 0) continue;

                                        const newRow = row + dr;
                                        const newCol = col + dc;

                                        // 判断边界
                                        if (
                                                newRow >= 0 &&
                                                newRow < Minesweeper_GameData.row &&
                                                newCol >= 0 &&
                                                newCol < Minesweeper_GameData.col
                                        ) {
                                                const newGrid = Minesweeper_GameData.arrGrids[newRow][newCol];
                                                if (newGrid && !newGrid.是否翻开 && !newGrid.是否插旗) {
                                                        this.forceRevealCell(newRow, newCol); // 递归展开
                                                }
                                        }
                                }
                        }
                }
        }
        toggleFlag(row: number, col: number) {
                const grid = Minesweeper_GameData.arrGrids[row][col];

                if (grid.是否翻开) return; // 已经翻开不能插旗

                grid.是否插旗 = !grid.是否插旗; // 切换插旗状态
                grid.Refresh();

                Minesweeper_GamePanel.Instance.Refresh_mines();
        }
        revealCell(row: number, col: number) {
                const grid = Minesweeper_GameData.arrGrids[row][col];

                // 1. 已经翻开或插旗，不能再处理
                if (grid.是否翻开 || grid.是否插旗) return;

                // 2. 处理第一次点击（生成雷区）
                if (Minesweeper_GameManager.Instance) {
                        Minesweeper_GameManager.Instance.handleFirstClick(row, col);
                }

                // 3. 翻开当前格子
                grid.是否翻开 = true;
                Minesweeper_GameData.已翻格子数++;
                grid.Refresh();

                // 4. 胜利判断
                const 总格子数 = Minesweeper_GameData.row * Minesweeper_GameData.col;
                const 雷数 = Minesweeper_GameData.雷数量;

                if (Minesweeper_GameData.已翻格子数 === 总格子数 - 雷数) {
                        console.log("恭喜！你赢了！");
                        Minesweeper_GameManager.Instance.Win();
                        return;
                }

                // 5. 如果是雷，游戏结束（这里只处理翻开，不做UI逻辑）
                if (grid.是否是雷) {
                        console.log("踩雷了！");
                        Minesweeper_GameManager.Instance.Lose();
                        return;
                }

                // 6. 如果周围有雷，只翻开自己
                if (grid.周围雷数量 > 0) {
                        return;
                }

                // 7. 如果周围没有雷，递归展开周围格子
                for (let dr = -1; dr <= 1; dr++) {
                        for (let dc = -1; dc <= 1; dc++) {
                                if (dr === 0 && dc === 0) continue;

                                const newRow = row + dr;
                                const newCol = col + dc;

                                // 判断边界
                                if (
                                        newRow >= 0 &&
                                        newRow < Minesweeper_GameData.row &&
                                        newCol >= 0 &&
                                        newCol < Minesweeper_GameData.col
                                ) {
                                        this.revealCell(newRow, newCol); // 递归展开
                                }
                        }
                }
        }
        Refresh() {
                // 只有在翻开后才显示雷
                this.雷.active = this.是否翻开 && this.是否是雷;

                // 旗子始终可见（如果插旗的话）
                this.旗子.active = this.是否插旗;

                // 只有在翻开且不是雷时才显示数字
                if (this.Label_count) {
                        this.Label_count.node.active = this.是否翻开 && !this.是否是雷 && this.周围雷数量 > 0;
                        this.Label_count.string = `${this.周围雷数量}`;

                        // 根据周围雷数量设置不同颜色
                        switch (this.周围雷数量) {
                                case 1:
                                        this.Label_count.color = new Color().fromHEX('#00C3EF'); // 蓝色
                                        break;
                                case 2:
                                        this.Label_count.color = new Color().fromHEX('#31B642'); // 绿色
                                        break;
                                case 3:
                                        this.Label_count.color = new Color().fromHEX('#FF5D52'); // 红色
                                        break;
                                case 4:
                                        this.Label_count.color = new Color().fromHEX('#00C3EF'); // 深蓝色
                                        break;
                                case 5:
                                        this.Label_count.color = new Color().fromHEX('#FF9231'); // 深红色
                                        break;
                                case 6:
                                        this.Label_count.color = new Color().fromHEX('#008284'); // 青色
                                        break;
                                case 7:
                                        this.Label_count.color = new Color().fromHEX('#840084'); // 紫色
                                        break;
                                case 8:
                                        this.Label_count.color = new Color().fromHEX('#757575'); // 灰色
                                        break;
                                default:
                                        this.Label_count.color = Color.BLACK; // 默认黑色
                                        break;
                        }
                }

                // 未翻开的图片在未翻开时显示
                this.未翻开图片.active = !this.是否翻开;

                this.Label_pos.string = `col-${this.col}\nrow-${this.row}`;
                this.Label_pos.node.active = false;
        }
        GetNodeWorldPostation(_node: Node): Vec3 {
                let pos: Vec3 = v3();
                if (_node.parent == null) {
                        pos = v3(_node.getPosition());
                } else {
                        // pos = v3(_node.parent.convertToWorldSpaceAR(_node.getPosition()));
                        pos = _node.getWorldPosition();
                }
                return pos;
        }
        //    // 初始化单元宽高
        InitWidthAndHeight(cardWidth?: number, cardHeight?: number) {
                if (cardWidth) this.node.getComponent(UITransform).width = cardWidth;
                if (cardHeight) this.node.getComponent(UITransform).height = cardHeight;
        }
        //    // 初始化位置
        InitPosition() {
                //     let x = -Minesweeper_GameData.W / 2 + this.node.width / 2 + this.node.width * (this.col - 1);
                //     let y = -Minesweeper_GameData.H / 2 + this.node.height / 2 + this.node.height * (this.row - 1);
                let x = -Minesweeper_GameData.W / 2 + this.node.getComponent(UITransform).width / 2 + this.node.getComponent(UITransform).width * (this.col - 0);
                let y = -Minesweeper_GameData.H / 2 + this.node.getComponent(UITransform).height / 2 + this.node.getComponent(UITransform).height * (this.row - 0);
                this.node.position = v3(x, y, 0);
        }
        async Flash() {
                let duration = 0.2;
                this.red.active = true;
                await new Promise(res => this.scheduleOnce(res, duration));

                this.red.active = false;

                await new Promise(res => this.scheduleOnce(res, duration));

                this.red.active = true;
                await new Promise(res => this.scheduleOnce(res, duration));

                this.red.active = false;

                await new Promise(res => this.scheduleOnce(res, duration));

                this.red.active = true;
                await new Promise(res => this.scheduleOnce(res, duration));

                this.red.active = false;
        }
}